<?php
namespace app\admin\controller;
use think\Db;
class Adminuser extends Base
{
    public function info()
    {
        if(is_post()){
            $data = input();
            unset($data['avatar']);
            $rule = [
                'email'      =>  'email',
                'password'   =>  'min:6',
            ];
            $msg = [
                'email.email'   =>  '邮箱格式错误',
                'password.min'  =>  '密码长度不能小于6位数',
            ];
            com_validate($rule, $msg, $data, true);
            
            //上传图片
            if( isset($_FILES['avatar']) ){
                $pic = com_up_pic('avatar', 'avatar', true);
                $data['avatar'] = $pic;
                com_check(['err'=>['js_action'=>'alert'], 'suc'=>['return_type'=>'return']] );
            //删除图片
            }
            if( isset($data['delete_avatar']) ){
                unset($data['delete_avatar']);
                if(!isset($_FILES['avatar']))
                    $data['avatar'] = '';
            }
            
            //修改密码
            if(!empty($data['password'])){
                $data['password'] = com_password($data['password']);
            }else{
                unset( $data['password'] );
            }
            $data['id'] = com_admininfo('id');
            Db::name('admin_user')->update($data);
            com_check( ['suc'=>['msg'=>'修改成功!', 'js_action'=>'alert|reload']] );
        }
        $data = [
            'nav'       => ['控制面板', '个人信息'],
            'info'      => Db::name('admin_user')->find( com_admininfo('id') ),
        ];
        return view('', $data);
    }
    public function lists(){
        
        //ajax查询数据
        if( is_post() ){
            $page     = input('page');
            $status   = input('status');
            $keyword  = input('keyword');
            $min_time = input('min_time');
            $max_time = input('max_time');
            
            
            //原生态sql查询
            $sql = "
                SELECT
                    [1]
                FROM
                    admin_user
                WHERE 
                    1 = ?
                ";
            $param = [1];
            if ( $status != '100all' ) {
                $sql .= " status = ?";
                $param[] = $status;
            }
            if ( !empty($keyword) ) {
                $sql .= " and (username like ? or name like ?)";
                $param[] = "%{$keyword}%";
                $param[] = "%{$keyword}%";
            }
            if ( !empty($min_time) ) {
                $sql    .= " and create_time >= ?";
                $param[] = strtotime($min_time);
            }
            if ( !empty($max_time) ) {
                $sql    .= " and create_time <= ?";
                $param[] = strtotime($max_time);
            }
            //总条数
            $sql_count = str_replace("[1]", "count(*) as total", $sql);
            $total     = Db::query($sql_count, $param);
            $total     = $total[0]['total'];
            
            //分页数据
            $page_size   = c('page_size');     #分页条数
            $page        = com_cur_page($total, $page,  $page_size);   #当前页
            $page_data   = com_page_data($total, $page,  $page_size);   #分页原始数据
            
            //列表数据
            $start       = ($page - 1) * $page_size;
            $sql        .= " order by id desc limit $start, $page_size";
            $field       = "*";
            $sql_list    = str_replace("[1]", $field, $sql);
            $list        = Db::query($sql_list, $param);
            //格式数据
            foreach($list as $k => $v){                
                $list[$k]['checkbox']       =  com_format_checkbox($v['id']);
                $list[$k]['status']         =  com_format_status2(url('ajax/editStatus', 't=admin_user'),$v['id'],$v['status']);
                $list[$k]['create_time']    =  com_format_time( $v['create_time'] );
                
                $list[$k]['action'] = "";
                if($v['role_ids']=='superman'){
                    $list[$k]['role_ids'] = "超级管理员";
                    $list[$k]['status'] = "";
                }else{
                    $rs = Db::name('admin_role')->where("id","in", $v['role_ids'])->column("title");
                    $list[$k]['role_ids'] = implode(",", $rs);
                    $list[$k]['action']        .=  com_action_edit( url("adminuser/edit","id={$v['id']}"), $v['id'], '编辑用户' );
                    $list[$k]['action']        .=  com_action_del( url("adminuser/delete","t=admin_user"), $v['id'], "你确定要删除{$v['name']}吗？" );
                }
            }
            $com_body    = com_build_table($list, array("checkbox","username", "phone" ,"role_ids", "status", "create_time","action"));
            $com_page    = com_build_page( $page_data );
            $data = array(
                "com_body"  => $com_body,
                "com_page"  => $com_page,
            );
            $config = [
                'data'   => $data,
                'suc'    => [
                    'js_action' => 'function.switchs',
                ],
            ];
            com_check($config);
        }


        $data = [
            'status'    => ['100all'=>'全部状态'] + c('type.status'),
            'nav'       => ['员工列表', '列表'],
        ];
        return view('', $data);
    }



    //添加
    public function add(){
        if( is_post() ){
            $data = input();
            //验证
            $rule = [
                'username'      =>  'require',
                'password'      =>  'require|min:6',
                's_password'    =>  'require|min:6',
                'role_ids'    =>  'require',
            ];
            $msg = [
                'username.require'       =>  '登陆账号不能为空',
                'password.require'       =>  '登陆密码不能为空',
                'password.min'       =>  '登陆密码至少6位数',
                's_password.require'     =>  '操作密码不能为空',
                's_password.min'       =>  '操作密码至少6位数',
                'role_ids.require'       =>  '请选择所属部门',
            ];
            com_validate( $rule, $msg, $data, true );
            $data['role_ids'] = ",".implode(",", $data['role_ids']).",";
            $data['create_time'] = time();
            $data['password']    = com_password($data['password']);
            $data['s_password']  = com_password($data['s_password']);
            Db::name('admin_user')->insert($data);
            $config = [
                'msg' => '添加员工成功！',
                'suc' => [
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        }    
        //模板赋值
        $data = [
            'list' => Db::name('admin_role')->select(),
        ];
        return view('', $data);
    }


    //编辑
    public function edit( $id ){
        if( is_post() ){
            $data = input();
            //验证
            $rule = [
                'username'      =>  'require',
                'phone'         =>  'require',
                'password'      =>  'min:6',
                's_password'    =>  'min:6',
                'role_ids'    =>  'require',
            ];
            $msg = [
                'username.require'       =>  '登陆账号不能为空',
                'phone.require'          =>  '手机号不能为空',
                'password.min'         =>  '登陆密码至少6位数',
                's_password.min'       =>  '操作密码至少6位数',
                'role_ids.require'     =>  '请选择所属部门',
            ];
            com_validate( $rule, $msg, $data, true );
            $data['role_ids'] = ",".implode(",", $data['role_ids']).",";
            $data['update_time'] = time();
            if(!empty($data['password'])){
                $data['password'] = com_password($data['password']);
            }else{
                unset($data['password']);
            }
            if(!empty($data['s_password'])){
                $data['s_password'] = com_password($data['s_password']);
            }else{
                unset($data['s_password']);
            }
            Db::name('admin_user')->update($data);
            $config = [
                'msg' => '编辑员工成功！',
                'suc' => [
                    'js_action' => 'alert|close',
                ],
            ];
            com_check( $config );
        }    
        //模板赋值
        $info = Db::name('admin_user')->find($id);
        $role_ids = explode(",", $info['role_ids']);
        $data = [
            'info'      => $info,
            'role_ids'  => $role_ids,
            'list'      => Db::name('admin_role')->select(),
        ];
        return view('', $data);
    }




    //删除
    public function delete(){
        if( is_post() ){
            $id  =  input('id');
            $role_ids = Db::name('admin_user')->where('id',$id)->value('role_ids');
            if( $role_ids=='superman' ){
                com_error(['超级管理员不能删除']);
            }else{
                Db::name('admin_user')->delete($id);
            }   
    
            $config = [
                'suc' => [
                    'msg'       => '删除成功!',
                    'js_action' => 'alert|reload',
                ],
                'err' => [
                    'js_action' => 'alert',
                ]
            ];
            com_check($config);
        }
    }
    
    //批量删除
    public function delall(){
        if( is_post() ){
    
            $ids = input('ids/a');
            $a   = new \app\admin\model\AdminRole();
    
            foreach($ids as $id){
                $role_ids = Db::name('admin_user')->where('id',$id)->value('role_ids');
                if( $role_ids=='superman' ){
                    com_error(['超级管理员不能删除']);
                }else{
                    Db::name('admin_user')->delete($id);
                }
            }
            $config = [
                'err' => [
                    'js_action' => "alert|reload",
                ],
                'suc' => [
                    'msg' => '删除成功！',
                    'js_action'=>"alert|reload",
                ],
            ];
            com_check($config);
        }
    }
}
